package com.siki.salessystemoauth2server.config.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.siki.salessystemcommon.entity.enumeration.GlobalServiceMsgCode;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

public class MyOauthExceptionSerializer extends StdSerializer<MyOauthException> {

    protected MyOauthExceptionSerializer() {
        super(MyOauthException.class);
    }

    @Override
    public void serialize(MyOauthException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("code",GlobalServiceMsgCode.USER_TOKEN_EXPIRED.getCode());
        jsonGenerator.writeStringField("msg", GlobalServiceMsgCode.USER_TOKEN_EXPIRED.getMessage());
        jsonGenerator.writeStringField("data",e.getMessage());
        jsonGenerator.writeEndObject();
    }
}
